import shutil
import sys
import time
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta

import pandas as pd
from tqdm import tqdm
import os

beginDate = datetime.strptime("2024-01-01","%Y-%m-%d")
endDate = datetime.strptime("2024-01-20","%Y-%m-%d")
dataCPFDir = "../dataset/dataCPF/"
dataPreciseDir = "../dataset/dataPrecise"
dateRes = {}


def mjd_to_date(mjd):
    # 基准日期：1858-11-17 00:00:00（MJD=0）
    base_date = datetime(1858, 11, 17)
    # MJD 是天数，直接加即可
    return base_date + timedelta(days=mjd)

def sod_to_time(sod):
    """将秒数（SOD）转换为时间（HH:MM:SS）"""
    return timedelta(seconds=sod)


def get_file_paths(directory):
    file_paths = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            file_paths.append(os.path.normpath(file_path))
    return file_paths


if __name__ == "__main__":
    filePaths= get_file_paths(dataCPFDir)
    if os.path.exists(dataPreciseDir):
        shutil.rmtree(dataPreciseDir)
    if not os.path.exists(dataPreciseDir):
        os.makedirs(dataPreciseDir)


    t_bar = tqdm(filePaths, total=len(filePaths))
    for filePath in t_bar:
        fileName = filePath.split("_")[2]
        fileName = f"20{fileName}"
        start_time = datetime.strptime(fileName,"%Y%m%d")
        t_bar.set_description(f"{start_time.strftime('%Y-%m-%d')}")
        with open(filePath, 'r') as f:
            lines = f.readlines()
            for line in lines:
                if line.startswith('10'):
                    dataMsg = line.split()
                    mjd = int(dataMsg[2])  # 第3列是 MJD
                    sod = float(dataMsg[3])  # 第4列是 SOD
                    x, y, z = map(float, dataMsg[5:8])
                    dateNow = mjd_to_date(mjd)
                    if dateNow < start_time:
                        continue
                    elif dateNow == start_time:
                        dateTime = mjd_to_date(mjd) + sod_to_time(sod)
                        if (dateTime.hour * 60 + dateTime.minute) % 6 != 0:
                            continue
                        dateName = dateNow.strftime('%Y-%m-%d')
                        if dateName in dateRes:
                            dateRes[dateName].append([dateTime,x,y,z])
                        else:
                            dateRes[dateName] = []
                            dateRes[dateName].append([dateTime,x,y,z])
                    else:
                        break

    for date, data in dateRes.items():
        writePath = f"../dataset/dataPrecise/{date}.csv"
        df = pd.DataFrame(data, columns=["date", "X", "Y", "Z"])
        df['date'] = pd.to_datetime(df['date'])
        df.to_csv(writePath, index=False)